package com.tl.web05.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter extends HttpFilter {
    private final List<String> notFilterList = Arrays.asList("/login.jsp", "/ajax_register", "/ajax_login", "/register.jsp", "/captcha", ".js", ".css");

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        try {
            String servletPath = req.getServletPath();
            for (String s : notFilterList) {
                if (servletPath.endsWith(s)) {
                    chain.doFilter(req, res);
                    return;
                }
            }
            //判断是否登录
            HttpSession session = req.getSession();
            Boolean isLogin = (Boolean) session.getAttribute("isLogin");
            if (!isLogin) {
                res.sendRedirect(req.getContextPath() + "/login.jsp");
                return;
            }
            chain.doFilter(req, res);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
